<?php
namespace App\Console\Commands;
/**
计划任务执行生成的文件权限
**/

trait SetUserAndGroup
{
	public $user = 'www';
    public $group = 'www';

    //设置所属用户和用户组
    public function setUserAndGroup()
    {
        // get uid
        $user_info = posix_getpwnam($this->user);
        if(!$user_info)
        {
            return \Log::info( "Waring: User {$this->user} not exsits");
        }
        $uid = $user_info['uid'];
        // get gid
        if($this->group)
        {
            $group_info = posix_getgrnam($this->group);
            if(!$group_info)
            {
                return \Log::info( "Waring: Group {$this->group} not exsits");
            }
            $gid = $group_info['gid'];
        }
        else
        {
            $gid = $user_info['gid'];
        }

        // set uid and gid
        if($uid != posix_getuid() || $gid != posix_getgid())
        {
            if(!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid))
            {
                \Log::info( "Waring: change gid or uid fail.");
            }
        }
    }
}

